﻿using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Diagnostics;
using System.IO;
using System.Web.Script.Serialization;
using Localization;
using SinBiota.Model.Business.OccurrenceServices.Implementation;
using SinBiota.Model.Entities;
using SinBiota.Model.Persistence.SessionManager;


namespace TaxonomyMigration
{
    class Program
    {
        static void Main(string[] args)
        {
            //TestInclusion();
            var connectionFactory = new ConnectionFactory();
            var taxonomyServices = new TaxonomyServices(connectionFactory);
            var classificationList = new List<IDictionary<string, string>>();
            var idList = new List<string>();
            var originalClassList = new List<string>();
            var connection = new SqlConnection("Server=localhost;Initial Catalog=sinbiotav11;User Id=sinbiota;Password=8wU$t6za;");
            var sw = new Stopwatch();
            sw.Start();
            try
            {
                using (connection)
                {
                    connection.Open();
                    var tr = new StreamReader("D:\\users\\pedro\\Documents\\scylla\\biota\\taxonomy\\taxonomy_migration_sheets\\taxa_summary_spp_summary_06_2012.csv");
                    while (!tr.EndOfStream)
                    {
                        var s = tr.ReadLine().Split('\t');
                        var ids = s[0];
                        var originalClass = s[1];
                        idList.Add(ids);
                        originalClassList.Add(originalClass);
                        classificationList.Add(new TaxonomicClassification {LegacyTaxonomicClassification = s[1]}.LegacyTaxonomyLocalizedToDictionary());

                        //if (taxDict.ContainsKey(Taxonomy.genero))
                        //{
                        //    if (taxDict.ContainsKey(Taxonomy.especie))
                        //    {
                        //        list.Add(taxDict.ContainsKey(Taxonomy.subespecie)
                        //                     ? new[] {Functions.UppercaseFirst(taxDict[Taxonomy.genero]),taxDict[Taxonomy.especie], taxDict[Taxonomy.subespecie]}
                        //                     : new[] {Functions.UppercaseFirst(taxDict[Taxonomy.genero]),taxDict[Taxonomy.especie]});
                        //    }
                        //    else
                        //    {
                        //        list.Add(new []{Functions.UppercaseFirst(taxDict[Taxonomy.genero]) });
                        //    }
                            
                        //}
                        //else
                        //{
                        //    foreach (var rank in new [] {Taxonomy.familia, Taxonomy.classe, Taxonomy.ordem, Taxonomy.filo, Taxonomy.reino, Taxonomy.dominio})
                        //    {
                        //         parse rank;
                        //    }
                        //}
                       
                    }
                    Console.WriteLine(String.Format("Encontradas {0} entradas.", classificationList.Count));
                    //Functions.ParseClassification(list, connection);
                    var results = taxonomyServices.ParseClassification(classificationList); //.Take(10).ToList());
                    //foreach (var pair in classificationList.Zip(results, (x,y) => new {classification = x, result = y}))
                    //{
                    //    var classification = pair.classification;
                    //    var result = pair.result;
                    //    Console.WriteLine(String.Join(", ", classification.Select(x => string.Format("{1} ({0})", x.Key, x.Value))));
                    //    Console.WriteLine(result.TaxonSimilarities[0].Name);
                    //    Console.WriteLine();
                    //}
                    var writer = new StreamWriter("D:\\users\\pedro\\Documents\\scylla\\biota\\taxonomy\\taxonomy_migration_sheets\\taxa_summary_spp_summary_06_2012_MS_class.csv");
                    for (var i = 0; i < results.Count; i++)
                    {
                        var result = results[i].TaxonSimilarities[0];
                        var ids = idList[i];
                        var cl = originalClassList[i];
                        writer.WriteLine("{0}\t{1}\t{2}\t{3}\t{4}",ids, cl, result.TaxonId,result.Name,result.Similarity);
                    }
                    writer.Close();
                    Console.WriteLine(@"Elapsed time:{0}", sw.ElapsedMilliseconds / 1000.0);

                }
            }
            finally
            {
                connection.Dispose();
            }
        }
        static void TestInclusion()
        {
            var addList = new List<string[]>();
            var tr = new StreamReader("D:\\users\\pedro\\Documents\\scylla\\biota\\taxonomy\\taxonomy_migration_sheets\\taxa_summary_spp_summary_COL_06_2012_latin1.csv");
            while (!tr.EndOfStream)
            {
                var s = tr.ReadLine().Split('\t');
                var ids = s[0];
                var taxonomy = new TaxonomicClassification {LegacyTaxonomicClassification = s[1]};
                var taxDict = taxonomy.LegacyTaxonomyLocalizedToDictionary();
                //var a = JsonConvert.DeserializeObject
                var jss = new JavaScriptSerializer();
                try
                {
                    var col = jss.Deserialize<dynamic>(s[2]);
                    var result = col["results"][0];
                    var rank = result["rank"];
                    if (rank.Equals("genus") && taxDict.ContainsKey(Taxonomy.especie))
                    {
                        addList.Add(new string[] {result["name"], taxDict[Taxonomy.especie]});
                    }
                }
                catch (Exception)
                {
                    
                    //Console.WriteLine("Invalid line:");
                   // Console.WriteLine(s[2]);
                }
                
            }
            Console.WriteLine("{0} especies serao adicionadas.", addList.Count);
            addList.Sort((a, b) => 2*a[0].CompareTo(b[0]) + a[1].CompareTo(b[1]));
            foreach (var s in addList)
            {
                Console.WriteLine("Genus {0} -> {1}",s[0],s[1]);
            }
        }
        public class ColClassification
        {
            public class OneClassification
            {
                public int distance { get; set; }
                public int id { get; set; }
                public int parent_id { get; set; }
                public string rank { get; set; }
            }
            public int max_distance { get; set; }
            public string search { get; set; }
            public List<OneClassification> results { get; set; }

        }
    }
}
